<template>
  <div class="app-container" v-loading="loading">
    <div class="flex flex-wrap">
      <div class="flex justify-between w-full p-b-5">
        <div class="font-black text-xl"><!-- 地市统计分析 --></div>
        <el-row :gutter="10">
          <el-col :span="7">
            <el-date-picker
              style="width: 100%"
              v-model="queryParams.dateArr"
              type="daterange"
              range-separator="-"
              value-format="YYYY-MM-DD"
              start-placeholder="开始时间"
              end-placeholder="结束时间"
              @change="getLevel"
            />
          </el-col>
          <el-col :span="7">
            <el-tree-select
              class="w-full"
              :disabled="userStore.userInfo.orgId != 484"
              v-model="queryParams.deptIdArr"
              placeholder="请选择公司"
              default-expand-all
              multiple
              :data="companyOption"
              :props="{
                value: 'id',
                label: 'label',
                children: 'children'
              }"
              @change="getLevel"
            />
          </el-col>
          <el-col :span="7">
            <el-select
              class="w-full"
              v-model="queryParams.isTax"
              placeholder="是否含税"
              @change="getLevel"
            >
              <el-option
                v-for="item in yes_or_no"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              /> </el-select
          ></el-col>
          <el-col :span="3" class="text-right">
            <el-button icon="Download" @click="exportExcel('地市统计分析')"
              >导出</el-button
            >
          </el-col>
        </el-row>
      </div>
      <div class="min-h-300px w-full">
        <el-table
          ref="levelTable"
          :data="tableData"
          style="width: 100%"
          border
          stripe
          @cell-click="cellClick"
          show-summary
          :summary-method="getSummaries"
          :sum-text="'统计'"
        >
          <el-table-column
            type="index"
            label="排名"
            align="center"
            width="60"
            fixed="left"
          />
          <el-table-column
            prop="deptName"
            label="地区"
            fixed="left"
            width="160"
          >
            <template #default="scope">
              <dict-drop
                :options="bidding_unit"
                :value="scope.row.deptId"
              ></dict-drop>
            </template>
          </el-table-column>
          <el-table-column
            v-for="(item, index) in tableLevel"
            :key="index"
            :prop="
              item.children && item.children.length ? undifined : item.prop
            "
            v-bind="item"
          >
            <template v-if="item.children && item.children.length">
              <el-table-column
                v-for="(item1, index1) in item.children"
                :key="index1"
                v-bind="item1"
              >
              </el-table-column>
            </template>
          </el-table-column>
          <el-table-column prop="percentage" label="销售占比" min-width="160">
            <template #default="scope">
              <span
                class="inline-block w-4/6 bg-slate-100 h-10px rounded-full overflow-hidden"
              >
                <span
                  class="inline-block bg-sky-300 h-10px align-top"
                  :style="{ width: `${scope.row.percentage}%` }"
                ></span>
              </span>
              {{ scope.row.percentage }}%</template
            >
          </el-table-column>
        </el-table>
      </div>
    </div>
  </div>
</template>
<script setup name="LevelTable">
import { reactive, toRefs, ref } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { statisticsLevel } from '@/api/nztStatistics/index'
import { strToArr } from '@/utils/commo'
import {
  companyOption //所属公司
} from '@/hooks/dict/order'
import useUserStore from '@/store/modules/user'
import FileSaver from 'file-saver'
import * as XLSX from 'xlsx'
const userStore = useUserStore()
const router = useRouter()
const route = useRoute()
const { proxy } = getCurrentInstance()
const {
  bidding_unit, //内部单位
  yes_or_no, //是否
  fiscal_statement_type //是否
} = proxy.useDict('bidding_unit', 'yes_or_no', 'fiscal_statement_type')
const data = reactive({
  queryParams: {
    dateArr: [],
    deptIdArr: []
  },
  tableData: []
})
let { queryParams, tableData } = toRefs(data)

function goTo(url, data) {
  router.push({ path: url, query: data })
}

// 点击地市统计分析单元格
function cellClick(row, column, cell, event) {
  let levetKey = tableLevel.value.filter(e => e.prop == column.property)
  if (levetKey.length == 0) return
  let obj = {
    deptId: row.deptId,
    receiptsDates: queryParams.value.dateArr,
    businessType: levetKey[0].dictValue
  }
  console.log('obj==>', obj)
  // goTo('/sales/indent/salesOrder', { salesOrderData: JSON.stringify(obj) })
}

const tableLevel = ref([
  {
    show: true,
    prop: 'contractOrderNumber1',
    label: '诺账通精益版',
    align: 'center',
    showOverflowTooltip: true,
    children: [
      {
        show: true,
        prop: 'num1',
        label: '数量',
        align: 'center',
        width: 160,
        showOverflowTooltip: true
      },
      {
        show: true,
        prop: 'totalPrice1',
        label: '金额',
        align: 'center',
        width: 160,
        showOverflowTooltip: true
      }
    ]
  },
  {
    show: true,
    prop: 'contractOrderNumber2',
    label: '诺账通标准版',
    align: 'center',
    showOverflowTooltip: true,
    children: [
      {
        show: true,
        prop: 'num2',
        label: '数量',
        align: 'center',
        width: 160,
        showOverflowTooltip: true
      },
      {
        show: true,
        prop: 'totalPrice2',
        label: '金额',
        align: 'center',
        width: 160,
        showOverflowTooltip: true
      }
    ]
  },
  {
    show: true,
    prop: 'contractOrderNumber3',
    label: '诺账通畅享版',
    align: 'center',
    showOverflowTooltip: true,
    children: [
      {
        show: true,
        prop: 'num3',
        label: '数量',
        align: 'center',
        width: 160,
        showOverflowTooltip: true
      },
      {
        show: true,
        prop: 'totalPrice3',
        label: '金额',
        align: 'center',
        width: 160,
        showOverflowTooltip: true
      }
    ]
  },
  {
    show: true,
    prop: 'contractOrderNumber4',
    label: '诺账通增强版',
    align: 'center',
    showOverflowTooltip: true,
    children: [
      {
        show: true,
        prop: 'num4',
        label: '数量',
        align: 'center',
        width: 160,
        showOverflowTooltip: true
      },
      {
        show: true,
        prop: 'totalPrice4',
        label: '金额',
        align: 'center',
        width: 160,
        showOverflowTooltip: true
      }
    ]
  },
  {
    show: true,
    prop: 'total',
    label: '合计',
    align: 'center',
    showOverflowTooltip: true,
    children: [
      {
        show: true,
        prop: 'totalNum',
        label: '数量',
        align: 'center',
        width: 160,
        showOverflowTooltip: true
      },
      {
        show: true,
        prop: 'businessTotalPrice',
        label: '金额',
        align: 'center',
        width: 160,
        showOverflowTooltip: true
      }
    ]
  }
])

const loading = ref(false)
// 地市分析
function getLevel() {
  loading.value = true
  statisticsLevel(queryParams.value)
    .then(ref => {
      tableData.value = ref.data
      loading.value = false
      // console.log('ref==>', ref)
    })
    .catch(() => {
      loading.value = false
    })
}
getLevel()

const getSummaries = param => {
  const { columns, data } = param
  const sums = []
  columns.forEach((column, index) => {
    if (index === 0) {
      sums[index] = '合计'
      return
    }
    const values = data.map(item => {
      let property = strToArr(column.property, '.')
      return property.length > 1
        ? Number(item[property[0]][property[1]])
        : Number(item[column.property])
    })
    if (!values.every(value => isNaN(value))) {
      sums[index] = values.reduce((prev, curr) => {
        const value = Number(curr)
        return prev + (isNaN(value) ? 0 : value)
      }, 0)
    } else {
      sums[index] = ''
    }
  })
  return sums
}

const showColu = ref(true)
// 前端导出excel
const exportExcel = excelName => {
  let tableBox = {
    expireTable: '服务到期人数分析',
    levelTable: '地市统计分析',
    industryTable: '培训业务分类'
  }
  let tableRef = ''
  for (let key in tableBox) {
    console.log('导出key==>', key)
    if (tableBox[key] === excelName) {
      tableRef = key
    }
  }
  showColu.value = false
  setTimeout(() => {
    try {
      const $e = proxy.$refs[tableRef].$el
      let $table = $e.querySelector('.el-table__fixed')
      if (!$table) {
        $table = $e
      }

      const wb = XLSX.utils.table_to_book($table, { raw: true })
      const wbout = XLSX.write(wb, {
        bookType: 'xlsx',
        bookSST: true,
        type: 'array'
      })
      FileSaver.saveAs(
        new Blob([wbout], { type: 'application/octet-stream' }),
        `${excelName}.xlsx`
      )
      showColu.value = true
    } catch (e) {
      showColu.value = true
      if (typeof console !== 'undefined') console.error(e)
    }
  }, 500)
}
</script>
<style lang="scss" scoped>
.el-radio-group.groupBtn :deep(.el-radio__input) {
  display: none;
}
</style>
